<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/hexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="开发笔记,">










<meta name="description" content="最近写了一个支持大文件分片上传的小工具，算不上好吧，但还是想拿出来简单分析一下。当前几乎所有的cms系统都会有上传文件的需求，而要上传的文件除了文档，图片等小型文件外，偶尔也会遇到上传大的视频文件，压缩包等等，这时候就要用到分片上传的功能。如果是内网环境下，我们可以考虑使用ftp来上传大文件，但大多数情况我们都是在外网环境下进行上传的，当然也可以配置ftp来上传，但少不了一番折腾，而且还会造成很大">
<meta name="keywords" content="开发笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="分享一个支持断点续传的大文件分片上传的小模块">
<meta property="og:url" content="https://tony_df.coding.net/2020/06/29/分享一个支持断点续传的大文件分片上传的小模块/index.html">
<meta property="og:site_name" content="Tony&#39;s blog">
<meta property="og:description" content="最近写了一个支持大文件分片上传的小工具，算不上好吧，但还是想拿出来简单分析一下。当前几乎所有的cms系统都会有上传文件的需求，而要上传的文件除了文档，图片等小型文件外，偶尔也会遇到上传大的视频文件，压缩包等等，这时候就要用到分片上传的功能。如果是内网环境下，我们可以考虑使用ftp来上传大文件，但大多数情况我们都是在外网环境下进行上传的，当然也可以配置ftp来上传，但少不了一番折腾，而且还会造成很大">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tony_df.coding.net/2020/06/29/分享一个支持断点续传的大文件分片上传的小模块/2.png">
<meta property="og:image" content="https://tony_df.coding.net/2020/06/29/分享一个支持断点续传的大文件分片上传的小模块/1.png">
<meta property="og:updated_time" content="2020-06-29T12:12:53.583Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分享一个支持断点续传的大文件分片上传的小模块">
<meta name="twitter:description" content="最近写了一个支持大文件分片上传的小工具，算不上好吧，但还是想拿出来简单分析一下。当前几乎所有的cms系统都会有上传文件的需求，而要上传的文件除了文档，图片等小型文件外，偶尔也会遇到上传大的视频文件，压缩包等等，这时候就要用到分片上传的功能。如果是内网环境下，我们可以考虑使用ftp来上传大文件，但大多数情况我们都是在外网环境下进行上传的，当然也可以配置ftp来上传，但少不了一番折腾，而且还会造成很大">
<meta name="twitter:image" content="https://tony_df.coding.net/2020/06/29/分享一个支持断点续传的大文件分片上传的小模块/2.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hexo/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Tony'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tony_df.coding.net/2020/06/29/分享一个支持断点续传的大文件分片上传的小模块/">





  <title>分享一个支持断点续传的大文件分片上传的小模块 | Tony's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hexo/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学着码代码,学着码人生;</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tony_df.coding.net/hexo/2020/06/29/分享一个支持断点续传的大文件分片上传的小模块/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hexo/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">分享一个支持断点续传的大文件分片上传的小模块</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-06-29T19:24:35+08:00">
                2020-06-29
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>最近写了一个支持大文件分片上传的小工具，算不上好吧，但还是想拿出来简单分析一下。<br>当前几乎所有的cms系统都会有上传文件的需求，而要上传的文件除了文档，图片等小型文件外，偶尔也会遇到上传大的视频文件，压缩包等等，这时候就要用到分片上传的功能。<br>如果是内网环境下，我们可以考虑使用ftp来上传大文件，但大多数情况我们都是在外网环境下进行上传的，当然也可以配置ftp来上传，但少不了一番折腾，而且还会造成很大的安全隐患。<br>分片上传是走的http协议的，优点就是安全，方便，缺点就是速度慢，而且http上传大文件会有网络限制等问题，所以就需要进行分片上传。<br>当然了，分片上传的代码现在在网上一搜一箩筐，但其实原理都一样，对照代码来看一下<br>先来看接收端</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task&lt;ActionResult&gt; <span class="title">UploadFile</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Response resp = <span class="keyword">new</span> Response();</span><br><span class="line">    <span class="keyword">var</span> data = Request.Form.Files[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">string</span> f_md5 = Request.Form[<span class="string">"f_md5"</span>].ToString();</span><br><span class="line">    <span class="keyword">var</span> total = Request.Form[<span class="string">"total"</span>];</span><br><span class="line">    <span class="keyword">var</span> fileName = Request.Form[<span class="string">"fileName"</span>];</span><br><span class="line">    <span class="keyword">var</span> index = Request.Form[<span class="string">"index"</span>];</span><br><span class="line">    <span class="keyword">var</span> lesson_id = Request.Form[<span class="string">"lesson_id"</span>];</span><br><span class="line">    <span class="keyword">var</span> is_rewrite = Request.Form[<span class="string">"rewrite"</span>];</span><br><span class="line">    <span class="keyword">string</span> temporary = Path.Combine(<span class="string">$"<span class="subst">&#123;Directory.GetCurrentDirectory()&#125;</span>\\wwwroot\\upfile"</span>, f_md5);<span class="comment">//临时保存分块的目录</span></span><br><span class="line">    <span class="keyword">if</span> (redis.HashExists(<span class="string">"upload_list"</span>, f_md5))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//这里是判定上传记录的逻辑，如果该文件上传过，返回一个指定的状态码，提醒用户是重新上传还是跳过，代码不贴了，纯业务代码，用的redis的hash结构</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">try</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">bool</span> mergeOk = <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (!Directory.Exists(temporary))</span><br><span class="line">            Directory.CreateDirectory(temporary);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">string</span> filePath = Path.Combine(temporary, index.ToString());</span><br><span class="line">        <span class="comment">//如果该文件上传过，且没有上传完成，执行如下续传逻辑</span></span><br><span class="line">        <span class="comment">//如果只有一个文件,直接删掉，如果大于一个文件，为了保证文件完整性，把最后一个文件删掉，继续上传；</span></span><br><span class="line">        <span class="keyword">if</span> (index.ToString() == <span class="string">"0"</span> &amp;&amp; System.IO.File.Exists(filePath) &amp;&amp; is_rewrite.ToString()!=<span class="string">"y"</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            resp.code = <span class="number">2</span>;</span><br><span class="line">            resp.message = <span class="string">$"<span class="subst">&#123;fileName&#125;</span>已上传，开始续传"</span>;</span><br><span class="line">            <span class="keyword">var</span> files = Directory.GetFiles(temporary);</span><br><span class="line">            <span class="keyword">if</span> (files.Length &gt; <span class="number">1</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//把标号最大的文件删掉；</span></span><br><span class="line">                <span class="keyword">string</span> last_file = files.OrderByDescending(u =&gt; u.Length).ThenByDescending(u =&gt; u).First();</span><br><span class="line">                System.IO.File.Delete(last_file);</span><br><span class="line">                resp.data = <span class="keyword">new</span> &#123; index = files.Length - <span class="number">2</span>, total, mergeOk, fileName &#125;;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">                System.IO.File.Delete(filePath);</span><br><span class="line">            <span class="keyword">return</span> Json(resp);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!Convert.IsDBNull(data))</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">await</span> Task.Run(() =&gt;</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">using</span> (FileStream fs = <span class="keyword">new</span> FileStream(filePath, FileMode.Create))</span><br><span class="line">                &#123;</span><br><span class="line">                    data.CopyTo(fs);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (total == index)</span><br><span class="line">        &#123;</span><br><span class="line">            mergeOk = <span class="keyword">await</span> FileMerge(f_md5, fileName, lesson_id);</span><br><span class="line">            <span class="keyword">if</span> (mergeOk)</span><br><span class="line">                <span class="keyword">await</span> redis.HashSetAsync(<span class="string">"upload_list"</span>, f_md5, <span class="string">"success"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        resp.code = <span class="number">1</span>;</span><br><span class="line">        resp.message = <span class="string">$"<span class="subst">&#123;index&#125;</span>/<span class="subst">&#123;total&#125;</span>上传完成"</span>;</span><br><span class="line">        resp.data = <span class="keyword">new</span> &#123; index, total, mergeOk, fileName &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> Json(resp);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Exception ex)</span><br><span class="line">    &#123;</span><br><span class="line">        Directory.Delete(temporary);<span class="comment">//删除文件夹</span></span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//合并文件</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task&lt;<span class="keyword">bool</span>&gt; <span class="title">FileMerge</span>(<span class="params"><span class="keyword">string</span> f_md5, <span class="keyword">string</span> fileName, <span class="keyword">string</span> lesson_id</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">bool</span> ok = <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">try</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> temporary = Path.Combine(<span class="string">$"<span class="subst">&#123;Directory.GetCurrentDirectory()&#125;</span>\\wwwroot\\upfile"</span>, f_md5);<span class="comment">//临时文件夹</span></span><br><span class="line">        fileName = Request.Form[<span class="string">"fileName"</span>];<span class="comment">//文件名</span></span><br><span class="line">        <span class="keyword">string</span> fileExt = Path.GetExtension(fileName);<span class="comment">//获取文件后缀</span></span><br><span class="line">        <span class="keyword">var</span> files = Directory.GetFiles(temporary);<span class="comment">//获得下面的所有分片文件</span></span><br><span class="line">        <span class="keyword">string</span> tmp_filepath = Guid.NewGuid().ToString(<span class="string">"N"</span>);</span><br><span class="line">        <span class="keyword">string</span> finalPath = <span class="string">$"<span class="subst">&#123;en.WebRootPath&#125;</span>\\upfile\\<span class="subst">&#123;DateTime.Now.ToString(<span class="string">"yyyyMM"</span>)&#125;</span>\\<span class="subst">&#123;f_md5&#125;</span>"</span>;</span><br><span class="line">        <span class="keyword">if</span> (!Directory.Exists(finalPath))</span><br><span class="line">            Directory.CreateDirectory(finalPath);</span><br><span class="line">        finalPath += <span class="string">$"\\<span class="subst">&#123;fileName&#125;</span>"</span>;</span><br><span class="line">        <span class="keyword">using</span> (<span class="keyword">var</span> fs = <span class="keyword">new</span> FileStream(finalPath, FileMode.Create))</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">foreach</span> (<span class="keyword">var</span> part <span class="keyword">in</span> files.OrderBy(x =&gt; x.Length).ThenBy(x =&gt; x))<span class="comment">//排一下序，保证从0-N Write</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">var</span> bytes = System.IO.File.ReadAllBytes(part);</span><br><span class="line">                <span class="keyword">await</span> fs.WriteAsync(bytes, <span class="number">0</span>, bytes.Length);</span><br><span class="line">                bytes = <span class="literal">null</span>;</span><br><span class="line">                System.IO.File.Delete(part);<span class="comment">//删除分块</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        Directory.Delete(temporary);<span class="comment">//删除文件夹</span></span><br><span class="line">        ok = <span class="literal">true</span>;</span><br><span class="line">        <span class="comment">//复制到附件服务器</span></span><br><span class="line">        <span class="keyword">await</span> CopyFileAsync(finalPath, f_md5 + <span class="string">"\\"</span> + fileName, <span class="literal">true</span>);</span><br><span class="line">        Directory.Delete(finalPath);</span><br><span class="line"></span><br><span class="line">        <span class="meta">#<span class="meta-keyword">region</span> 更新数据</span></span><br><span class="line">        <span class="comment">//这里也是业务代码，设计更新库表记录，不贴了</span></span><br><span class="line">        <span class="meta">#<span class="meta-keyword">endregion</span></span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Exception ex)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ok;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第一段就是用来接收客户端上传的分片文件，第二段就是合并文件；<br>第一段里有一段根据文件名的md5值来判定文件是否已经上传过，就是当接受第一个分片文件时，根据该文件md5值来判定，如果有，则返回当前已经接收的文件最大索引值，从而实现断点续传的功能。<br>至此，支持分片上传的服务端代码就完成了，再来看看客户端<br>一般我们常使用浏览器来进行上传，类似的js代码网上也数不胜数，我就不贴我的js代码了，因为这个接口除了页面再用，还有一个上传工具也在用，而这个工具是个控制台程序，所以我这里分享下上传文件的C#代码。<br>在页面端，我们可以通过设定请求的特定参数，来方便的提交文件信息，而后台代码原理是一样的。<br>这里我们除了自己构造httprequest参数，也可以采用一个第三方的类库RestSharp，来方便的进行，为什么推荐RestSharp呢，因为有一次看postman的提交代码，发现postman生成的c#代码里就是用的RestSharp进行的<br>表单模拟，所以就尝试用了一下，还不错。</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">async</span> Task&lt;<span class="keyword">bool</span>&gt; <span class="title">SliceUploadAsync</span>(<span class="params"><span class="keyword">string</span> filePath,<span class="keyword">string</span> lesson_id ,Func&lt;<span class="keyword">int</span>,<span class="keyword">int</span>&gt; displayProgress=<span class="literal">null</span></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">try</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">string</span> filename = Path.GetFileName(filePath);</span><br><span class="line">        <span class="keyword">string</span> md5 = CYSCC_NET.Common.Security.Md5(filename);</span><br><span class="line">        <span class="keyword">var</span> url = ConfigurationHelper.GetSectionValue(<span class="string">"upload_address"</span>);</span><br><span class="line">        <span class="keyword">var</span> client = <span class="keyword">new</span> RestClient(url);</span><br><span class="line">        client.Timeout = <span class="number">-1</span>;</span><br><span class="line">        <span class="keyword">var</span> request = <span class="keyword">new</span> RestRequest(Method.POST);</span><br><span class="line">        <span class="keyword">using</span> (FileStream fsRead = <span class="keyword">new</span> FileStream(filePath, FileMode.Open, FileAccess.Read))</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="comment">//文件总长度</span></span><br><span class="line">            <span class="keyword">long</span> left = fsRead.Length;</span><br><span class="line">            <span class="comment">//存储读取结果（这里设定成1Mb）</span></span><br><span class="line">            <span class="keyword">byte</span>[] bytes = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span> * <span class="number">1024</span>];</span><br><span class="line">            <span class="comment">//每次读取的最大长度  </span></span><br><span class="line">            <span class="keyword">int</span> maxLength = bytes.Length;</span><br><span class="line">            <span class="comment">//所有分段</span></span><br><span class="line">            <span class="keyword">int</span> total = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(left / <span class="number">1024</span> / <span class="number">1024</span>)));</span><br><span class="line">            <span class="comment">//分段文件索引</span></span><br><span class="line">            <span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line">            <span class="comment">//文件读取的起始位置</span></span><br><span class="line">            <span class="keyword">long</span> start = <span class="number">0</span>;</span><br><span class="line">            <span class="comment">//每次读取的长度</span></span><br><span class="line">            <span class="keyword">int</span> num = <span class="number">0</span>;</span><br><span class="line">            request.AddParameter(<span class="string">"f_md5"</span>, md5);</span><br><span class="line">            request.AddParameter(<span class="string">"total"</span>, total);</span><br><span class="line">            request.AddParameter(<span class="string">"fileName"</span>, filename);</span><br><span class="line">            request.AddParameter(<span class="string">"lesson_id"</span>, lesson_id);</span><br><span class="line">            <span class="keyword">while</span> (left &gt; <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                fsRead.Position = start;</span><br><span class="line">                num = <span class="number">0</span>;</span><br><span class="line">                <span class="keyword">if</span> (left &lt; maxLength)</span><br><span class="line">                    num = <span class="keyword">await</span> fsRead.ReadAsync(bytes, <span class="number">0</span>, Convert.ToInt32(left));</span><br><span class="line">                <span class="keyword">else</span></span><br><span class="line">                    num = <span class="keyword">await</span> fsRead.ReadAsync(bytes, <span class="number">0</span>, maxLength);</span><br><span class="line">                <span class="keyword">if</span> (num == <span class="number">0</span>)</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                <span class="keyword">if</span> (request.Files.Count &gt; <span class="number">0</span>)</span><br><span class="line">                    request.Files.RemoveAt(<span class="number">0</span>);</span><br><span class="line">                <span class="keyword">if</span> (request.Parameters.Count(u =&gt; u.Name == <span class="string">"index"</span>) &gt; <span class="number">0</span>)</span><br><span class="line">                    request.Parameters.Remove(request.Parameters.Where(u =&gt; u.Name == <span class="string">"index"</span>).FirstOrDefault());</span><br><span class="line">                request.AddFile(<span class="string">"data"</span>, bytes, filename);</span><br><span class="line">                request.AddParameter(<span class="string">"index"</span>, index);</span><br><span class="line">                IRestResponse response = <span class="keyword">await</span> client.ExecuteAsync(request);</span><br><span class="line">                <span class="keyword">if</span> (index == <span class="number">0</span>) &#123;</span><br><span class="line">                    Response resp = JsonHelper.JsonDeserialize&lt;Response&gt;(response.Content);</span><br><span class="line">                    <span class="keyword">if</span> (resp.code==<span class="number">2</span>)</span><br><span class="line">                    &#123;</span><br><span class="line">                        Console.ForegroundColor = ConsoleColor.Cyan;</span><br><span class="line">                        Console.WriteLine(<span class="string">$"\n<span class="subst">&#123;resp.message&#125;</span>\n"</span>);</span><br><span class="line">                        index = Convert.ToInt32(resp.data.index) - <span class="number">1</span>;</span><br><span class="line">                        <span class="keyword">if</span> (index &lt; <span class="number">0</span>)</span><br><span class="line">                            index = <span class="number">0</span>;</span><br><span class="line">                        start = index * maxLength;</span><br><span class="line">                        left = left - start;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">else</span> <span class="keyword">if</span> (resp.code == <span class="number">3</span>)</span><br><span class="line">                    &#123;</span><br><span class="line">                        <span class="comment">//重写逻辑，涉及业务内容，也不贴了</span></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (displayProgress != <span class="literal">null</span>) displayProgress(Convert.ToInt32(index / (total * <span class="number">1.0</span>) * <span class="number">100</span>));</span><br><span class="line">                start += num;</span><br><span class="line">                left -= num;</span><br><span class="line">                index++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        Console.ForegroundColor = ConsoleColor.Green;</span><br><span class="line">        Console.WriteLine(<span class="string">$"\n<span class="subst">&#123;filePath&#125;</span>上传成功...<span class="subst">&#123;DateTime.Now&#125;</span>"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span>(Exception ex)</span><br><span class="line">    &#123;</span><br><span class="line">        NLogUtil.fileLogger.Error(<span class="string">$"上传失败,<span class="subst">&#123;ex.Message&#125;</span>,<span class="subst">&#123;ex.StackTrace&#125;</span>"</span>);</span><br><span class="line">        Console.ForegroundColor = ConsoleColor.Red;</span><br><span class="line">        Console.WriteLine(<span class="string">$"上传失败:<span class="subst">&#123;ex.Message&#125;</span>"</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代码有些凌乱~简单说明一下<br>方法参数中的filePath就是文件的地址，第二个参数是业务参数，不解释，第三个时一个委托方法参数，为的输出上传进度，也不多说。<br>整段的代码逻辑就是，读取文件，每次读取1M字节流进行上传，同时传入上传的分段索引，md5值，总共的分段个数，文件名和其他业务参数。<br>其中，当上次第一个索引文件时，接收端会判断之前是否上传过该文件，如果上传过，则会返回指定的状态码，同时返回服务端的最大索引值，这样客户端就可以通过该索引值来继续进行上传。<br>也就是说，当我们在上传大文件的过程中，如果遇到断网，断电等情况时，也完全不用担心，下次恢复正常后，继续上传即可。<br>好了，至此，一个支持断点续传的大文件分片上传的小模块就完成了，看下效果图吧。<br><img src="2.png" alt="2"><br><img src="1.png" alt="1"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hexo/tags/开发笔记/" rel="tag"># 开发笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hexo/2020/06/21/薅bd的羊毛-2/" rel="next" title="薅bd的羊毛?-2（从百度网盘下载文件）">
                <i class="fa fa-chevron-left"></i> 薅bd的羊毛?-2（从百度网盘下载文件）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hexo/2020/08/11/断更了/" rel="prev" title="断更了...">
                断更了... <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5bbb2338b87602f0" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTA1My8xNTU4MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description">学习总结</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hexo/archives/">
              
                  <span class="site-state-item-count">58</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hexo/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/hexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

</body>
</html>
